<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>用户登录</h2>
        <p>欢迎使用澳玛小红书投放评估工具</p>
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            class="login-btn"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { tokenManager } from '@/utils/token'
import { login } from '@/api/port'
const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref<FormInstance>()
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  userName: '',
  password: ''
})

// 表单验证规则
const loginRules: FormRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    // { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    // { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    // 调用登录API
    const res = await login({
      userName: loginForm.userName,
      password: loginForm.password
    })
    console.log(res)
    // 检查登录是否成功
     if (res.data?.code === 0 && res.data) {
       // 如果API返回了token，使用API的token，否则生成模拟token（只包含必要的token信息）
      //  const token = res.data.data.token || (() => {
      //    const tokenPayload = {
      //      iat: Math.floor(Date.now() / 1000),
      //      exp: Math.floor(Date.now() / 1000) + 24 * 60 * 60 // 24小时后过期
      //    }
      //    return `${res.data.data.token}.${btoa(JSON.stringify(tokenPayload))}.mock_signature`
      //  })()
       
       // 只存储token和时效
       tokenManager.setToken(res.data.data.token)
       console.log(tokenManager.getToken())
       // 用户信息存储在store的其他字段中
        const userInfo = res.data.data || null
        
        userStore.userInfo = userInfo
        // 同时保存到localStorage以便下次初始化
        localStorage.setItem('userInfo', userInfo?JSON.stringify(userInfo):'')
      
      ElMessage.success('登录成功')
      
      // 跳转到原始页面或首页
      const redirect = router.currentRoute.value.query.redirect as string
      router.push(redirect || '/index')
    } else {
      ElMessage.error(res.data?.message || '登录失败，请检查用户名和密码')
    }
    
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="less" scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  
  .login-box {
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    
    .login-header {
      text-align: center;
      margin-bottom: 30px;
      
      h2 {
        color: #333;
        font-size: 28px;
        font-weight: 600;
        margin-bottom: 8px;
      }
      
      p {
        color: #666;
        font-size: 14px;
        margin: 0;
      }
    }
    
    .login-form {
      .el-form-item {
        margin-bottom: 20px;
      }
      
      .login-btn {
        width: 100%;
        height: 45px;
        font-size: 16px;
        font-weight: 500;
        border-radius: 8px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        
        &:hover {
          background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }
      }
    }
  }
}
</style>